package com.cccccc.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/8/22
 * 备注：
 * MyAccessDeniedHandler类是Spring Security的AccessDeniedHandler实现类，用于处理没有权限访问的请求。
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        HashMap<String, String> result = new HashMap<>(); // 创建一个HashMap对象
        result.put("code","403"); // 设置code为403
        result.put("msg","请求访问"+request.getRequestURI()+"时，没有权限访问"); // 设置msg为请求访问的URI没有权限访问
        response.setContentType("application/json;charset=utf-8"); // 设置响应内容类型为JSON格式
        response.getWriter().write(JSON.toJSONString(result)); // 将HashMap对象转换为JSON字符串并写入响应
    }
}
